package com.lmc.base.demo.ai.controller;

import com.alibaba.cloud.ai.tongyi.chat.TongYiChatClient;
import io.qifan.ai.dashscope.DashScopeAiChatModel;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;


/**
 * @author lmc
 * @Description: TODO
 * @Create 2024-07-25 23:49
 * @version: 1.0
 */
@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {

    @Resource
    private TongYiChatClient chatClient;

    @Resource
    private DashScopeAiChatModel dashScopeAiChatModel;

    @RequestMapping("/test")
    public String test() {
        return "test";
    }

    /**
     * 简单调用接口example 对话问答
     * @param message
     * @return
     */
    @RequestMapping("/example")
    public String example(@RequestParam("message") String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return chatClient.call(prompt).getResult().getOutput().getContent();
    }

    /**
     * 流式响应 对话问答
     * @param message
     * @param response
     * @return
     */
    @RequestMapping(value = "/stream", produces = "application/json;charset=utf-8")
    public Flux<String> stream(@RequestParam(value = "message", defaultValue = "1+1=?") String message, HttpServletResponse response) {

        return chatClient.stream(message);
    }

    /**
     * 非流式问答
     *
     * @param prompt 用户提问
     * @return org.springframework.ai.chat.model.ChatResponse
     */
    @GetMapping("chat")
    public String chat(@RequestParam String prompt) {
        ChatClient chatClient = ChatClient.create(dashScopeAiChatModel);
        return chatClient.prompt()
                // 输入单条提示词
                .user(prompt)
                // call代表非流式问答，返回的结果可以是ChatResponse，也可以是Entity（转成java类型），也可以是字符串直接提取回答结果。
                .call()
                .content();
    }




}
